from flask import Blueprint, request, jsonify
from src.models.models import db, SystemConfig, Subscription, DownloadTask, CrawlLog, DownloadQueue
from datetime import datetime, timedelta
import psutil
import os
from src.services.serial_generator import SerialGenerator
from src.models.license import SoftwareLicense
from src.services.network_info import NetworkInfoService

system_bp = Blueprint('system', __name__)

@system_bp.route('/system/status', methods=['GET'])
def get_system_status():
    """获取系统状态"""
    try:
        # 获取配置
        scheduler_enabled = SystemConfig.get_config('scheduler_enabled', 'false') == 'true'
        global_auto_download = SystemConfig.get_config('global_auto_download', 'false') == 'true'
        crawl_interval = int(SystemConfig.get_config('crawl_interval', '60'))  # type: ignore
        
        # 统计数据
        total_subscriptions = Subscription.query.count()
        active_subscriptions = Subscription.query.filter_by(is_active=True).count()
        auto_download_subscriptions = Subscription.query.filter_by(auto_download=True).count()
        
        total_downloads = DownloadTask.query.count()
        waiting_create_downloads = DownloadTask.query.filter_by(status='waiting_create').count()
        created_success_downloads = DownloadTask.query.filter_by(status='created_success').count()
        created_failed_downloads = DownloadTask.query.filter_by(status='created_failed').count()
        task_duplicate_downloads = DownloadTask.query.filter_by(status='task_duplicate').count()
        
        # 队列统计
        queued_tasks = DownloadQueue.query.filter_by(status='queued').count()
        processing_tasks = DownloadQueue.query.filter_by(status='processing').count()
        
        # 最近爬取统计
        today = datetime.now().date()
        today_crawls = CrawlLog.query.filter(
            CrawlLog.crawl_time >= today
        ).count()
        
        # 系统信息
        cpu_percent = psutil.cpu_percent(interval=1)
        memory = psutil.virtual_memory()
        disk = psutil.disk_usage('/')
        
        return jsonify({
            'success': True,
            'data': {
                'scheduler_enabled': scheduler_enabled,
                'global_auto_download': global_auto_download,
                'crawl_interval': crawl_interval,
                'subscriptions': {
                    'total': total_subscriptions,
                    'active': active_subscriptions,
                    'auto_download': auto_download_subscriptions
                },
                'downloads': {
                    'total': total_downloads,
                    'waiting_create': waiting_create_downloads,
                    'created_success': created_success_downloads,
                    'created_failed': created_failed_downloads,
                    'task_duplicate': task_duplicate_downloads
                },
                'queue': {
                    'queued': queued_tasks,
                    'processing': processing_tasks
                },
                'crawl_stats': {
                    'today_crawls': today_crawls
                },
                'system_info': {
                    'cpu_percent': round(cpu_percent, 1),
                    'memory_percent': round(memory.percent, 1),
                    'disk_percent': round((disk.used / disk.total) * 100, 1)
                }
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

@system_bp.route('/system/detailed_status', methods=['GET'])
def get_detailed_system_status():
    """获取详细系统状态"""
    try:
        # 基础状态
        basic_status = get_system_status()
        if not basic_status.json['success']:  # type: ignore
            return basic_status
        
        # 最近活动
        recent_subscriptions = Subscription.query.order_by(
            Subscription.updated_at.desc()
        ).limit(5).all()
        
        recent_downloads = DownloadTask.query.order_by(
            DownloadTask.created_at.desc()
        ).limit(10).all()
        
        recent_crawls = CrawlLog.query.order_by(
            CrawlLog.crawl_time.desc()
        ).limit(10).all()
        
        # 错误统计
        failed_crawls_today = CrawlLog.query.filter(
            CrawlLog.crawl_time >= datetime.now().date(),
            CrawlLog.status == 'failed'
        ).count()
        
        failed_downloads_today = DownloadTask.query.filter(
            DownloadTask.created_at >= datetime.now().date(),
            DownloadTask.status == 'created_failed'
        ).count()
        
        data = basic_status.json['data']  # type: ignore
        data.update({
            'recent_activity': {
                'subscriptions': [sub.to_dict() for sub in recent_subscriptions],
                'downloads': [task.to_dict() for task in recent_downloads],
                'crawls': [log.to_dict() for log in recent_crawls]
            },
            'error_stats': {
                'failed_crawls_today': failed_crawls_today,
                'failed_downloads_today': failed_downloads_today
            }
        })
        
        return jsonify({
            'success': True,
            'data': data
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

@system_bp.route('/system/config', methods=['GET'])
def get_system_config():
    """获取系统配置"""
    try:
        configs = SystemConfig.query.all()
        config_dict = {config.key: config.value for config in configs}
        
        return jsonify({
            'success': True,
            'data': {
                'scheduler_enabled': config_dict.get('scheduler_enabled', 'false') == 'true',
                'crawl_interval': int(config_dict.get('crawl_interval', '60')),  # type: ignore
                'global_auto_download': config_dict.get('global_auto_download', 'false') == 'true'
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

@system_bp.route('/system/config/scheduler', methods=['PUT'])
def update_scheduler_config():
    """更新定时任务配置"""
    try:
        data = request.get_json()
        enabled = data.get('enabled', False)
        
        SystemConfig.set_config('scheduler_enabled', 'true' if enabled else 'false', '全局定时任务开关')
        
        # 如果关闭定时任务，需要停止所有正在运行的任务
        if not enabled:
            from src.services.scheduler import stop_scheduler
            stop_scheduler()
        else:
            from src.services.scheduler import start_scheduler
            start_scheduler()
        
        return jsonify({
            'success': True,
            'message': f'定时任务已{"开启" if enabled else "关闭"}'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

@system_bp.route('/system/config/crawl_interval', methods=['PUT'])
def update_crawl_interval():
    """更新爬取间隔"""
    try:
        data = request.get_json()
        interval = data.get('interval', 60)
        
        # 验证间隔范围
        if not isinstance(interval, int) or interval < 1 or interval > 1440:
            return jsonify({
                'success': False,
                'message': '爬取间隔必须在1-1440分钟之间'
            }), 400
        
        SystemConfig.set_config('crawl_interval', str(interval), '爬取时间间隔（分钟）')
        
        # 重启定时任务以应用新间隔
        scheduler_enabled = SystemConfig.get_config('scheduler_enabled', 'false') == 'true'
        if scheduler_enabled:
            from src.services.scheduler import restart_scheduler
            restart_scheduler()
        
        return jsonify({
            'success': True,
            'message': f'爬取间隔已更新为{interval}分钟'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

@system_bp.route('/system/config/global_auto_download', methods=['PUT'])
def update_global_auto_download():
    """更新全局自动下载配置"""
    try:
        data = request.get_json()
        enabled = data.get('enabled', False)
        
        SystemConfig.set_config('global_auto_download', 'true' if enabled else 'false', '全局自动下载开关')
        
        # 同步更新所有订阅的自动下载状态
        if enabled:
            Subscription.query.update({'auto_download': True})
        else:
            # 如果关闭全局自动下载，不强制关闭单个订阅的自动下载
            pass
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': f'全局自动下载已{"开启" if enabled else "关闭"}'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500


@system_bp.route('/system/xunlei_nas_config', methods=['GET'])
def get_xunlei_nas_config():
    """获取迅雷NAS配置"""
    try:
        host = SystemConfig.get_config('xunlei_nas_host')
        credential = SystemConfig.get_config('xunlei_nas_credential')
        initial_dir_id = SystemConfig.get_config('xunlei_nas_initial_dir_id')
        device_space_id = SystemConfig.get_config('xunlei_nas_device_space_id')
        last_updated = SystemConfig.get_config('xunlei_nas_last_updated')

        return jsonify({
            'success': True,
            'data': {
                'host': host,
                'credential': credential,
                'initial_dir_id': initial_dir_id,
                'device_space_id': device_space_id,
                'last_updated': last_updated
            }
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500


@system_bp.route('/system/xunlei_nas_config', methods=['PUT'])
def update_xunlei_nas_config():
    """更新迅雷NAS配置"""
    try:
        data = request.get_json()
        host = data.get('host')
        credential = data.get('credential')
        initial_dir_id = data.get('initial_dir_id')
        device_space_id = data.get('device_space_id')

        # 后端校验：参数不能为空
        if not host or not credential or not initial_dir_id or not device_space_id:
            return jsonify({
                'success': False,
                'message': '所有迅雷NAS配置参数都不能为空'
            }), 400

        # 保存配置
        from datetime import datetime
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        SystemConfig.set_config('xunlei_nas_host', host, '迅雷NAS主机地址')
        SystemConfig.set_config('xunlei_nas_credential', credential, '迅雷NAS授权凭证')
        SystemConfig.set_config('xunlei_nas_initial_dir_id', initial_dir_id, '迅雷NAS初始目录ID')
        SystemConfig.set_config('xunlei_nas_device_space_id', device_space_id, '迅雷NAS设备空间ID')
        SystemConfig.set_config('xunlei_nas_last_updated', current_time, '迅雷NAS配置最后更新时间')

        db.session.commit()

        return jsonify({
            'success': True,
            'message': '迅雷NAS配置已保存'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500


@system_bp.route('/system/xunlei_nas_test', methods=['POST'])
def test_xunlei_nas_connection():
    """测试迅雷NAS连接"""
    try:
        data = request.get_json()
        host = data.get('host')
        credential = data.get('credential')

        if not host or not credential:
            return jsonify({
                'success': False,
                'message': '主机地址和授权凭证不能为空！'
            }), 400

        # 这里添加实际的迅雷NAS连接测试逻辑
        # 示例：发送HTTP请求测试连接
        import requests
        import urllib3
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

        try:
            # 构建测试请求
            test_url = f"{host.rstrip('/')}/webman/3rdparty/pan-xunlei-com/index.cgi/drive/v1/about"
            headers = {
                'pan-auth': f'{credential}',
                'Content-Type': 'application/json'
            }

            # 发送测试请求（设置较短的超时时间）
            response = requests.get(test_url, headers=headers, timeout=3, verify=False)

            if response.status_code == 200:
                return jsonify({
                    'success': True,
                    'message': '连接测试成功！'
                })
            else:
                return jsonify({
                    'success': False,
                    'message': f'连接失败，HTTP状态码：{response.status_code}'
                })

        except requests.exceptions.Timeout:
            return jsonify({
                'success': False,
                'message': '连接超时，请检查主机地址是否正确！'
            })
        except requests.exceptions.ConnectionError:
            return jsonify({
                'success': False,
                'message': '无法连接到主机，请检查主机地址和网络连接！'
            })
        except Exception as e:
            return jsonify({
                'success': False,
                'message': f'连接测试失败！：{str(e)}'
            })

    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500

@system_bp.route('/system/serial', methods=['GET'])
def get_serial_number():
    """获取系统序列号"""
    try:
        license_obj = SoftwareLicense.get_license()
        if not license_obj:
            return jsonify({'success': False, 'message': '未找到授权信息，请联系管理员。'}), 404
        return jsonify({
            'success': True,
            'data': {
                'serial': license_obj.serial,
                'created_at': license_obj.created_at.strftime('%Y-%m-%d %H:%M:%S') if license_obj.created_at else ''
            }
        })
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500

@system_bp.route('/system/network_info', methods=['GET'])
def get_network_info():
    """获取网络信息（从system_config表中获取）"""
    try:
        # 从system_config表中获取网络信息
        local_ip = SystemConfig.get_config('local_ip', '获取失败')
        public_ip = SystemConfig.get_config('public_ip', '获取失败')
        network_status = SystemConfig.get_config('network_status', '异常')
        port = SystemConfig.get_config('port', '5000')
        
        return jsonify({
            'success': True,
            'data': {
                'local_ip': local_ip,
                'public_ip': public_ip,
                'network_status': network_status,
                'port': port
            }
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        }), 500